package com.crazymakercircle.queue;

public class ArrayBlockingQueue{
	private Object[] array;		//数组
	private int takeIndex;			//头
	private int putIndex;			//尾
	private volatile int count;	//元素个数

	public ArrayBlockingQueue(int capacity){
		this.array = new Object[capacity];
	}
	
	//写入元素
	public synchronized void put(Object o) throws InterruptedException{
		//当队列满时，阻塞
		while(count == array.length){
			this.wait();
		}
		array[putIndex++] = o;
		if(putIndex ==array.length){
			putIndex = 0;
		}
		count++;
		//唤醒线程
		this.notifyAll();
	}

	//取出元素
	public synchronized Object take() throws InterruptedException{
		//当队列为空，阻塞
		while(count == 0){
			this.wait();
		}
		Object o = array[takeIndex++];
		if(takeIndex == array.length){
			takeIndex = 0;
		}
		count--;
		//唤醒线程
		this.notifyAll();
		return o;
	}
}